<template>
	<view class="my-login">
		<uni-icons type="contact-filled" size="100" color="#afafaf"></uni-icons>
		<button open-type="getUserInfo" @getuserinfo="getuserinfo">一键登录</button>
		<text>登录后尽享更多权益</text>
	</view>
</template>

<script>
	import {
		mapState, mapMutations
	} from 'vuex'
	export default {
		name: "my-login",
		data() {
			return {

			};
		},
		computed: {
			...mapState('user', ['redirectInfo'])
		},
		methods: {
			...mapMutations('user', ['setUserInfo', 'setToken']),
			async getuserinfo(e) {
				const {
					detail: res
				} = e
				if (res.errMsg !== "getUserInfo:ok") return uni.$showMsg('获取用户信息失败')
				// console.log(res.userInfo);
				// 保存用户信息
				this.setUserInfo(res.userInfo)
				// 得到 code
				const [err, loginRes] = await uni.login()
				// 判断
				// console.log(loginRes);
				if (err) return uni.$showMsg('登陆失败')
				// 定义一个参数对象
				const params = {
					encryptedData: res.encryptedData,
					rawData: res.rawData,
					iv: res.iv,
					signature: res.signature,
					code: loginRes.code
				}
				// 获取 token
				this.getToken(params)
			},
			async getToken(params) {
				// const res = await uni.$http.post('/api/public/v1/users/wxlogin', params)
				// console.log(res);
				const {
					data: res
				} = await uni.$http.post('/api/public/v1/users/wxlogin', params)
				// console.log(res)
				// 判断  老师的代码 实际开发时使用
				// if (res.meta.status !== 200) return uni.$showMsg()
				// 保存 token
				// this.setToken(res.message.token)

				// 没有开发者权限的模拟代码 开始
				res.message = {}
				res.message.token = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjYxLCJpYXQiOjE2NTcyNTM5MDcsImV4cCI6MTAwMTY1NzI1MzkwNn0.SD4PvUMF5FBgis6SoI5lE-7vfEwy_VqnVT94HJmt4Ao'
				console.log(res)
				this.setToken(res.message.token)
				// 没有开发者权限的模拟代码 结束
				
				// 没有开发者权限的模拟代码 直接写死token
				// this.setToken('Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjYxLCJpYXQiOjE2NTcyNTM5MDcsImV4cCI6MTAwMTY1NzI1MzkwNn0.SD4PvUMF5FBgis6SoI5lE-7vfEwy_VqnVT94HJmt4Ao')

				// this.setToken('Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjYxLCJpYXQiOjE2NTcyNTM5MDcsImV4cCI6MTAwMTY1NzI1MzkwNn0.SD4PvUMF5FBgis6SoI5lE-7vfEwy_VqnVT94HJmt4Ao')
				// console.log(res)
				// 提示登录成功
				uni.showToast({
					title: '登录成功'
				})
				
				// 判断 redirectInfo 是否存在数据
				if (this.redirectInfo && this.redirectInfo.openType) {
					// 跳转到对应的页面
					uni.switchTab({
						url: this.redirectInfo.url
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.my-login {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 200rpx;

		button {
			margin: 20rpx 0 40rpx 0;
			width: 80%;
			border-radius: 40rpx;
			color: #fff;
			background-color: #eb4450;

		}

		text {
			font-size: 12px;
			color: #a49696
		}
	}
</style>
